'use client';

import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { useToast } from '@/hooks/use-toast';
import { authClient } from '@/lib/auth-client';
import { shopFormSchema } from '@/service/actions/schema/shop';
import { signUpShop } from '@/service/actions/shop';
import { zodResolver } from '@hookform/resolvers/zod';
import { useRouter } from 'next/navigation';
import { useState, useTransition } from 'react';
import { useForm } from 'react-hook-form';
import type { z } from 'zod';
import { PoiSearchFormItem } from '../common/poi-search-form-item';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '../ui/form';

export default function ShopRegister() {
  const [isPending, startTransition] = useTransition();
  const { toast } = useToast();
  const [open, setOpen] = useState(false);
  const { replace } = useRouter();
  const form = useForm<z.infer<typeof shopFormSchema>>({
    resolver: zodResolver(shopFormSchema),
    defaultValues: {
      username: '',
      name: '',
      email: '',
      shopName: '',
      contactPhone: '',
      address: null,
      password: '',
      confirmPassword: '',
    },
  });

  const register = async (values: z.infer<typeof shopFormSchema>) => {
    if (!values.address)
      return toast({ title: '请选择地址', variant: 'destructive' });
    if (values.password !== values.confirmPassword)
      return toast({
        variant: 'destructive',
        title: '两次输入的密码不匹配',
      });
    startTransition(async () => {
      try {
        const { error } = await signUpShop(values);
        if (error) {
          toast({
            variant: 'destructive',
            title: error.message,
          });
          return;
        }
        toast({
          title: '注册成功,请等待跳转...',
        });
        await authClient.signIn.username(
          {
            username: values.username,
            password: values.password,
          },
          {
            onSuccess: () => {
              replace('/shop');
            },
            onError: () => {
              toast({
                variant: 'destructive',
                title: '跳转失败请手动登录',
              });
              setOpen(false);
            },
          },
        );
      } catch (error) {
        console.error(error);
        toast({
          variant: 'destructive',
          title: '注册失败,请重试',
        });
      }
    });
  };

  return (
    <Dialog open={open}>
      <DialogTrigger asChild>
        <span
          onClick={() => setOpen(true)}
          className="cursor-pointer hover:text-foreground"
        >
          商铺注册
        </span>
      </DialogTrigger>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>商铺注册</DialogTitle>
          <DialogDescription>请填写以下信息以注册商铺</DialogDescription>
        </DialogHeader>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(register)} className="space-y-2">
            <div className="grid grid-cols-2 gap-7">
              <FormField
                control={form.control}
                name="username"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>用户名</FormLabel>
                    <FormControl>
                      <Input placeholder="登录名" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>昵称</FormLabel>
                    <FormControl>
                      <Input placeholder="展示名" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="email"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>邮箱</FormLabel>
                    <FormControl>
                      <Input placeholder="邮箱" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="shopName"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>商铺名称</FormLabel>
                    <FormControl>
                      <Input placeholder="商铺名称" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="contactPhone"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>联系电话</FormLabel>
                    <FormControl>
                      <Input placeholder="联系电话" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <PoiSearchFormItem<typeof shopFormSchema>
                label="商铺地址"
                name="address"
                control={form.control}
              />
              <FormField
                control={form.control}
                name="password"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>密码</FormLabel>
                    <FormControl>
                      <Input
                        type="password"
                        placeholder="输入密码"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="confirmPassword"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>确认密码</FormLabel>
                    <FormControl>
                      <Input
                        type="password"
                        placeholder="再次输入密码"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <div className="flex justify-between pt-5">
              <Button
                type="button"
                variant="secondary"
                onClick={() => setOpen(false)}
              >
                取消
              </Button>
              <Button type="submit" disabled={isPending}>
                {isPending && (
                  <span className="animate-spin i-ri-loader-4-line" />
                )}
                注册
              </Button>
            </div>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
